﻿package
{
	
	/**
	 * ...
	 * @author ghost 11.01.09
	 */
	 
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;

	public class ScreenShock extends MovieClip
	{
		private static var shockTarget:Sprite;		//目标剪辑
		private static var shocking:Boolean;	//是否正在震屏
		private static var timeLeft:Number;	//当前震动剩余帧数
		private static var shockType:Number;	//当前震动类型
		private static var initX:Number;	//sTarget初始位置x
		private static var initY:Number;	//sTarget初始位置y
		private static var shockPathX:Array = new Array();		//振动路径X
		private static var shockPathY:Array = new Array();		//振动路径Y
		private static const type1PathX:Array = [0, 0, 0, 0, 0, 0];	//震动类型1路径
		private static const type1PathY:Array = [-16,12,-8,4,-2,0];
		private static const type2PathX:Array = [-8];	//震动类型2路径
		private static const type2PathY:Array = [0];
		
		
		public function ScreenShock(){
			
			
		}
		
		public static function setTarget(sTarget:Sprite):void
		{
			shockTarget = sTarget;
			shockTarget.addEventListener(Event.ENTER_FRAME, shockSrc,false,0,true);
			shocking = false;
			timeLeft = 0;
			initX = shockTarget.x;
			initY = shockTarget.y;
		}
		
		public static function addShock(sType:Number, sSwing:Number,sFrames:Number ):void 	{

		//目标，震动类型，振幅，振动时间
		//sType:0,随机阻尼振动
		//		1,纵向16px，6frame振动；
		//		2,
		//		3,
			
			shocking = true;
			shockType = sType;
			
			switch(sType) {
				case 0:
					timeLeft = sFrames;
					for (var i:int = 0; i < sFrames; i++ ) {
						var sDirection = Math.random() * Math.PI;
						shockPathX[i] = sSwing * (1 - (i / sFrames)) * Math.sin(sDirection);		//生成从 -sSwing 到 sSwing 的递减随机数
						shockPathY[i] = sSwing * (1 - (i / sFrames)) * Math.cos(sDirection);		//生成从 -sSwing 到 sSwing 的递减随机数
					}
					break;
					
				case 1:
					timeLeft = type1PathY.length;
					shockPathX = type1PathX.slice();			//数组浅复制，复制引用
					shockPathY = type1PathY.slice();
					//trace(shockPathX + "\n\n\n" + shockPathY);
					break;
				case 2:
					timeLeft = type2PathY.length;
					shockPathX = type2PathX.slice();			//数组浅复制，复制引用
					shockPathY = type2PathY.slice();
					//trace(shockPathX + "\n\n\n" + shockPathY);
					break;
			}
					
		}
		
		private static function shockSrc(e:Event):void 
		{
			if (shocking) {
				if (timeLeft) {
					shockTarget.x = initX + shockPathX[shockPathX.length - timeLeft];
					shockTarget.y = initY + shockPathY[shockPathY.length - timeLeft];
					timeLeft--;
				}
				else {
					shockTarget.x = initX;
					shockTarget.y = initY;
					shocking = false;
				}
			}
		}

	}
	
}